package com.daafan.minilib.activity;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.daafan.minilib.R;
import com.daafan.minilib.data.BookData;
import com.daafan.minilib.data.BookList;
import com.daafan.minilib.data.Library;
import com.daafan.minilib.data.VideoLesson;
import com.google.gson.Gson;

public class ShakeResultActivity extends BaseActivity {

	public static final String	RESULT_JSON_STRING	= "RESULT_JSON";

	ListView					listView_temp_books;
	TempBooksAdpater			mAdapter;

	private List<JSONObject>	jsonList			= new ArrayList<JSONObject>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_temp_books);

		initTopBar("摇一摇", R.drawable.back, 0);

		Bundle bundle = getIntent().getExtras();
		if (bundle != null) {
			parseResult(bundle.getString(RESULT_JSON_STRING));
		}

		listView_temp_books = (ListView) findViewById(R.id.listView_temp_books);

		mAdapter = new TempBooksAdpater();
		listView_temp_books.setAdapter(mAdapter);
	}

	@Override
	protected void onTopLeftClick() {
		back();
	}

	/**
	 * 处理摇出来的结果
	 * 
	 * @param jString
	 */
	private void parseResult(String jString) {
		try {
			int index = jString.indexOf("{");
			jString = jString.substring(index);

			JSONObject json = new JSONObject(jString);
			JSONArray array = json.getJSONArray("datas");

			for (int i = 0; i < array.length(); i++) {
				JSONObject item = array.getJSONObject(i);
				jsonList.add(item);
			}

		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	class TempBooksAdpater extends BaseAdapter {

		ViewHolder	holder;

		class ViewHolder {
			TextView	tv_name;
			TextView	tv_type;
			Button		btn_delete;
		}

		@Override
		public int getCount() {
			return jsonList.size();
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			if (convertView == null) {
				convertView = getLayoutInflater().inflate(R.layout.item_temp, null);

				holder = new ViewHolder();
				holder.tv_name = (TextView) convertView.findViewById(R.id.tv_temp_book);
				holder.tv_type = (TextView) convertView.findViewById(R.id.tv_temp_type);
				holder.btn_delete = (Button) convertView.findViewById(R.id.btn_temp_book_delete);
				holder.btn_delete.setVisibility(View.GONE);

				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			if (position % 2 == 0) {
				convertView.setBackgroundColor(getResources().getColor(R.color.temp_book_bg));
			} else {
				convertView.setBackgroundColor(Color.TRANSPARENT);
			}

			final JSONObject item = jsonList.get(position);

			String type = item.optString("type");
			if (type.contains("BOOK")) {
				holder.tv_name.setText(item.optString("bookname"));
				holder.tv_type.setText("电子图书");

			} else if (type.contains("MAGAZINE")) {
				holder.tv_name.setText(item.optString("magname"));
				holder.tv_type.setText("电子杂志");

			} else if (type.contains("LIBRARY")) {
				holder.tv_name.setText(item.optString("name"));
				holder.tv_type.setText("书刊检索");

			} else if (type.contains("VIDEO")) {
				holder.tv_name.setText(item.optString("name"));
				holder.tv_type.setText("视频课程");
			}

			convertView.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					String type = item.optString("type");
					final String code = item.optString("code");
					final String imei = ((TelephonyManager) getSystemService(TELEPHONY_SERVICE)).getDeviceId();

					if (type.contains("BOOK")) {
						// final BookData book = new BookData();
						final BookData book = new Gson().fromJson(item.toString(), BookData.class);
						book.pdfurl = imei(book.pdfurl, code, imei);

						showConfirmDialog("电子书下载", "是否确认下载 《" + book.getBookname() + "》", new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog, int which) {
								// 向电子书加入任务
								BookList bookList = new BookList();
								bookList.restore(mContext);
								bookList.add(mContext, book);

								Intent intent = new Intent(mContext, BookListActivity.class);
								intent.putExtra(BookListActivity.BOOK_ID, book.getBookid());
								startActivity(intent);

								finish();
							}
						});
					} else if (type.contains("MAGAZINE")) {

						showConfirmDialog("电子杂志", "是否确认下载 ?", new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog, int which) {
								Intent intent = new Intent(mContext, EJournalActivity.class);
								intent.putExtra(EJournalActivity.EJOURNAL_URL, imei(item.optString("apkurl"), code, imei));
								startActivity(intent);

								finish();
							}
						});
					} else if (type.contains("LIBRARY")) {

						final Library library = new Library();
						library.setLid(item.optInt("id"));// 因为id只能是主键，所以不能用gson
						library.setName(item.optString("name"));
						library.setUrl(imei(item.optString("url"), code, imei));

						showConfirmDialog("临时书架", "是否收藏 " + library.getName() + " 到临时书架 ", new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog, int which) {
								// 储存图书
								List<Library> list = db.findAllByWhere(Library.class, "lid=" + library.lid);

								// 没有相同的书
								if (list.size() == 0)
									db.save(library);
								else {
									db.deleteByWhere(Library.class, "lid=" + library.lid);
									db.save(library);
								}

								Intent intent = new Intent(mContext, TempBooksActivity.class);
								startActivity(intent);

								finish();
							}
						});
					} else if (type.contains("VIDEO")) {

						final VideoLesson video = new VideoLesson();
						video.setVid(item.optString("id"));
						video.setName(item.optString("name"));
						video.setCategory(item.optString("category"));
						video.setUrl(imei(item.optString("url"), code, imei));

						showConfirmDialog("视频课程", "是否收藏 " + video.getName() + " 到视频课程 ", new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog, int which) {
								// 保存视频课程
								List<VideoLesson> list = db.findAllByWhere(VideoLesson.class, "vid=\"" + video.vid + "\"");

								// 没有相同的书
								if (list.size() == 0)
									db.save(video);
								else {
									db.deleteByWhere(VideoLesson.class, "vid=\"" + video.vid + "\"");
									db.save(video);
								}

								Intent intent = new Intent(mContext, VideosActivity.class);
								startActivity(intent);

								finish();
							}
						});
					}

				}
			});
			return convertView;
		}

		private String imei(String url, String code, String imei) {
			String r_url = url;

			if (url.contains("?")) {
				r_url = url + "&code=" + code + "&imei=" + imei;
			} else {
				r_url = url + "?code=" + code + "&imei=" + imei;
			}

			return r_url;
		}
	}
}
